package com.hmall.item.web;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.dto.PageDTO;

import com.hmall.item.constants.MqConstants;

import com.hmall.item.pojo.Item;
import com.hmall.item.pojo.ItemDoc;
import com.hmall.item.service.IItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@Slf4j
@RestController
@RequestMapping("/item")
public class ItemController {

    @Autowired
    private IItemService itemService;

    @Autowired
    private RabbitTemplate template;

    @GetMapping("/list")
    public PageDTO<Item> getList(@RequestParam("page") Integer curPage, @RequestParam("size") Integer size){
        IPage<Item> page = new Page<>(curPage,size);
        itemService.page(page);
        List<Item> list = page.getRecords();
        long total = page.getTotal();
        return new PageDTO<>(total,list);
    }

    @GetMapping("/{id}")
    public Item getItem(@PathVariable("id") Long id){
        return itemService.getById(id);
    }

    @PostMapping
    public void addItem(@RequestBody Item item){
        if (item == null || "".equals(item.getName())
                || "".equals(item.getCategory())
                || "".equals(item.getBrand())
                || "".equals(item.getImage())
                || "".equals(item.getSpec())
                || item.getPrice() == null
                || item.getStock() == null){
            throw new RuntimeException("必要字段不全");
        }else {
            itemService.save(item);
        }
//        log.warn("商品信息为{}",item);
    }

    @PutMapping("/status/{id}/{status}")
    public void updateStatusById(@PathVariable("id") Long id, @PathVariable("status") Integer status){
        Item item = new Item();
        item.setId(id);
        item.setStatus(status);
        itemService.updateById(item);
        ItemDoc itemDoc = new ItemDoc(getItem(id));
        String jsonString = JSON.toJSONString(itemDoc);
        if (status == 1){
            template.convertAndSend(MqConstants.HMALL_EXCHANGE,MqConstants.UP_KEY,jsonString);
        }else {
            template.convertAndSend(MqConstants.HMALL_EXCHANGE,MqConstants.DOWN_KEY,id);
        }

    }

    @PutMapping
    public void updateById(@RequestBody Item item){
//        log.warn("参数为{}",item);
        itemService.updateById(item);
    }

    @DeleteMapping("/{id}")
    public void deleteById(@PathVariable("id") Long id){
        itemService.removeById(id);
    }

}
